package com.etoak.service.impl;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.redis.RedisService;
import com.etoak.common.web.context.LoginContext;
import com.etoak.entity.Cart;
import com.etoak.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisService redisService;

    @Override
    public void saveOrUpdate(Cart cart) {
        redisService.hest(
                getRedisKey(),
                cart.getDishesId().toString(),
                JSONUtil.toJsonStr(cart));
    }

    @Override
    public List<Cart> getList() {
        return redisService.hvals(getRedisKey()).stream().map(json -> JSONUtil.toBean(json,Cart.class)).toList();
    }

    @Override
    public void delete(String dishesId) {
        redisService.hdel(getRedisKey(),dishesId);
    }

    @Override
    public void clear() {
        redisService.del(getRedisKey());
    }

    // 获取用户购物车redis key =》 cart:user:userID
    private String getRedisKey(){
        return CommonConstant.REDIS_CART_KEY + LoginContext.getUserId();
    }



}
